﻿using System;

namespace Cloak.Mvvm.Bindings
{
	/// <summary>
	/// A view model which may be bound to a source object
	/// </summary>
	public abstract class BoundModel : ViewModel, IViewModelBinding
	{
		private readonly BoundModelBinding _binding;

		/// <summary>
		/// Initializes a view model with an empty binding
		/// </summary>
		protected BoundModel()
		{
			_binding = new BoundModelBinding(() => RaisePropertyChanged("IsModified"));
		}

		#region IViewModelBinding
		/// <summary>
		/// Gets whether this view model's data differs from the source data
		/// </summary>
		public bool IsModified
		{
			get { return _binding.IsModified; }
		}

		/// <summary>
		/// Occurs when the value of the <see cref="IsModified"/> property changes
		/// </summary>
		public event EventHandler IsModifiedChanged
		{
			add { _binding.IsModifiedChanged += value; }
			remove { _binding.IsModifiedChanged -= value; }
		}

		/// <summary>
		/// Reads from the source object and sets values on this view model
		/// </summary>
		public void BindFromSource()
		{
			_binding.BindFromSource();
		}

		/// <summary>
		/// Reads from this view model and sets values on the source object
		/// </summary>
		public void BindToSource()
		{
			_binding.BindToSource();
		}
		#endregion

		/// <summary>
		/// Gets or sets the binding applied to this view model
		/// </summary>
		protected IViewModelBinding Binding
		{
			get { return _binding.Binding; }
			set { _binding.Binding = value; }
		}
	}
}